<!-- 批量新增 -->
<template>
	<view class="">
		<view class="uni-page-head" v-if="titleFlag">
			<image class="common-title-img" style="left: 20rpx;"
				:src="require('../../static/imges/fanhui.png')" @click="back()"></image>
				<!-- <view class="common-title-img">
					<u-icon name="arrow-right" color="#FFFFFF" width="20rpx" height="20rpx" size="48" @click="back()"></u-icon>
				</view> -->
				
				
			<view class="uni-page-head-title">
				批量新增验工计价
			</view>
		</view>
		<view v-if="titleFlag" style="margin-top: 98rpx;">
			<!-- 这个盒子是用来撑空间，又不想改变下边的body盒子 所以在这加了一个空盒子，可以根据新老MOA判断 -->
		</view>
		<view style="margin: 10px 10px; color:#646C9A">
			<text >请勾选需要验工计价的服务</text>
		</view>

		<view style="width: 100%; margin-top: 10px;" v-for="(item,index) in addlist" :key="index">
			
			
			<view>
				
			  <checkbox-group @change.stop="checkboxChange">
			<uni-collapse >


				<uni-collapse-item>
					<template v-slot:title>
						<view class="" style="height: 40px; display: flex;justify-content:space-between">
							
							
							<view class="" style="line-height: 40px;">
								<text  :selectable="true">{{item.name}}</text>
							</view>
							
							<view style="line-height: 40px;margin-right: 15px;">
								<checkbox :value="item.valuationId" :checked="item.flag" @click.stop.native="()=>{}"/>
							</view>

						</view>
					</template>


					<view class="common-body-ex" >
						<view class="common-list-ex-patch">

							<label class="common-list-title-ex">付款类型 :</label>
							<text class="common-list-text-ex-patch">进度款</text>

						</view>
						<view class="common-list-ex-patch2">

							<label class="common-list-title-ex"><text class="colorRed">*</text>项目进度（%）:</label>

							<input :disabled="!item.flag" @input="inputClick(index)" class="common-list-inpur-ex" type="number" 
							v-model="item.projectProgress" />

						</view>
						<view class="common-list-ex-patch2">

							<label class="common-list-title-ex"><text class="colorRed">*</text>本期验工数量 :</label>

							<input :disabled="!item.flag"  @input="blurclick(index)" class="common-list-inpur-ex" type="number" 
							 v-model="item.currentInspectionNum"  />

						</view>

						<view class="common-list-ex-patch2">

							<label class="common-list-title-ex"><text class="colorRed">*</text>本期验工金额(元):</label>

							<input :disabled="!item.flag" @input="blurclickMen(index)" class="common-list-inpur-ex" type="number" 
							 v-model="item.currentInspectionMoney"  />

						</view>
						<!-- <view class="common-list-ex-patch">

							<label class="common-list-title-ex">单价（元） :</label>

							<text class="common-list-text-ex-patch">{{item.value7}}</text>

						</view> -->

						<view class="common-list-ex-patch">

							<label class="common-list-title-ex">累计验工数量 :</label>

							<text class="common-list-text-ex-patch">{{leijiNum}}</text>

						</view>
						<view class="common-list-ex-patch">

							<label class="common-list-title-ex">累计验工金额 :</label>

							<text class="common-list-text-ex-patch">{{leijiMen}}</text>

						</view>
					</view>
				</uni-collapse-item>
			</uni-collapse> </checkbox-group>
			</view>
		</view>
		<view class="common-btn-body">
			<button class="common-btn" type="warn" @click="save()">批量新增</button>
			<button class="common-btn" @click="quxiao()" style="border:1px solid #EB4B4B;color:#EB4B4B ;">取消</button>
		</view>

	</view>
</template>

<script>
	import talkingdata from '../../common/talkingdata.js';
	var mThis
	export default {
		data() {
			return {

				aaa:"#2979ff",
				baseList: [],
				addlist: [],
				alerts: '',
				accordion: false,
				
				prjId: '',
				leijiNum: '0',
				leijiMen: '0',
				disabledNum:false,
				disabledMen:false,
				titleFlag:true
			}
		},
		onLoad(option) {
			mThis = this
			this.prjId = option.prjId
			console.log("this.prjId==" + this.prjId)
			if(uni.getStorageSync('moaType')=="0"){
					this.titleFlag=false
			}
			this.getList();


		},
		onReady(){
			console.log("执行onReady")
			
			//在页面挂载完成后，调用外部埋点，统计数据
			 const script= document.createElement('script');
			 script.type = 'text/javascript';
			 script.src = talkingdata.talkingKey;
			 document.body.appendChild(script);
			
		},
		// onBackPress(options) {
		// 	if (options.from === 'navigateBack') {
		// 		console.log("触发1")
		// 		return false;
		// 	}
		// 	console.log("触发2")
		// 	this.back();
		// 	return true;
		// },
		methods: {
			back() {
				//console.log("触发3")
				uni.navigateBack({
					delta: 1
				});
			},
			checkboxChange(e){
				let values = e.detail.value;
				console.log("选择的值"+values)
				for (let i = 0, lenI = this.addlist.length; i < lenI; ++i) {
				                    const item = this.addlist[i]
				                    if(values.includes(item.valuationId)){
				                        this.$set(item,'flag',true)
				                    }else{
				                        this.$set(item,'flag',false)
				                    }
				                }
			},
			quxiao(){
				this.baseList=[];
				this.addlist=[];
				this.getList();
				// uni.navigateBack({
				// 	delta: 1
				// })
			},
			focClick(){
				console.log("获取焦点")
			},
			inputClick(index){
				 let price = JSON.parse(JSON.stringify(this.addlist[index].projectProgress));
				 
				      price = price
				        .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
				        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
				        .replace(".", "$#$")
				        .replace(/\./g, "")
				        .replace("$#$", ".")
				        .replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
				      if (price.length > 8) {
				        //限制最多输入八位字符
				        price = price.slice(0, 8);
				      }
				      if (price.indexOf(".") < 0 && price != "") {
				        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
				        price = parseFloat(price);
				      }
				      //this.currentjindu = price;
				 console.log("1触发校验"+price)
				 setTimeout(() => {
				    this.addlist[index].projectProgress = price;
				 }, 100)
				  
			
				
			},
			blurclick(index){
				console.log("下表位置="+index)
			//控制保留4位start
			let val = JSON.parse(JSON.stringify(this.addlist[index].currentInspectionNum));
			
			     val = val
			       .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
			       .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
			       .replace(".", "$#$")
			       .replace(/\./g, "")
			       .replace("$#$", ".")
			       .replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');  // 只能输入四个小数
			     if (val.length > 8) {
			       //限制最多输入八位字符
			       val = val.slice(0, 8);
			     }
			     if (val.indexOf(".") < 0 && val != "") {
			       // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
			       val = parseFloat(val);
			     }
			     //this.currentjindu = val;
			console.log("1触发校验"+val)
			setTimeout(() => {
			  this.addlist[index].currentInspectionNum = val;
			}, 100)
			//end
				
				if(this.baseList[index].onlyBe1Flag == "N"){
					//if(this.addlist[index].currentInspectionNum != undefined && this.currentNum != ""){
						this.addlist[index].currentInspectionMoney = this.baseList[index].price * this.addlist[index].currentInspectionNum
						this.addlist[index].currentInspectionMoney = this.addlist[index].currentInspectionMoney.toFixed(4);// 只能输入四个小数
						this.leijiNum = Number(this.baseList[index].sumNum)  + Number(this.addlist[index].currentInspectionNum)
						this.leijiNum = this.leijiNum.toFixed(4);// 只能输入四个小数
						if(this.addlist[index].currentInspectionMoney){
							//console.log("触发"+this.currentMen);
								this.leijiMen = Number(this.baseList[index].sumMoney) + Number(this.addlist[index].currentInspectionMoney)
								this.leijiMen = this.leijiMen.toFixed(4);// 只能输入四个小数
						}
					
							//累计验工数量=预占数量时。  这个金额不能调整。 并且累计验工计价金额必须等于预占金额。
							// if(this.baseList[index].sumNum === this.baseList[index].shNum){
							// 	if(this.baseList[index].sumMoney === this.baseList[index].shMoney){
							// 		this.addlist[index].flag = true
							// 	}
								
							// }
							if(this.baseList[0].sumNum !== this.baseList[0].shNum && this.baseList[0].sumNum !==0){
								
								this.menflag = this.currentMen
								//console.log("等于1触发"+this.menflag);
								console.log("可以修改");
							}else{
								console.log("不能修改");
								this.disabledMen = true
							}
						
					//}
					
				}
				
			},
			blurclickMen(index){
				//控制保留4位start
				let val = JSON.parse(JSON.stringify(this.addlist[index].currentInspectionMoney));
				
				     val = val
				       .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
				       .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
				       .replace(".", "$#$")
				       .replace(/\./g, "")
				       .replace("$#$", ".")
				       .replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');  // 只能输入四个小数
				     if (val.length > 8) {
				       //限制最多输入八位字符
				       val = val.slice(0, 8);
				     }
				     if (val.indexOf(".") < 0 && val != "") {
				       // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
				       val = parseFloat(val);
				     }
				     //this.currentjindu = val;
				console.log("1触发校验"+val)
				setTimeout(() => {
				   this.addlist[index].currentInspectionMoney = val;
				}, 100)
				//end
				if(this.baseList[0].onlyBe1Flag == "N"){
					 if(this.currentNum == "1" && this.currentMen != ""){
						 this.blurClickMenOne();
					 }
				}
				console.log("触发")
				this.leijiMen = Number(this.baseList[index].sumMoney) + Number(this.addlist[index].currentInspectionMoney)
				this.leijiMen = this.leijiMen.toFixed(4);// 只能输入四个小数
			},
			blurClickMenOne(){
				let that=this;
				if(Number(this.currentMen) >(Number(this.menflag)+10) ||  Number(this.currentMen) <(Number(this.menflag)+10)){
					console.log("出错");
					uni.showModal({
						confirmColor: '#eb4b4b',
						title: '温馨提示',
						content: '验工计价金额只能在系统计算的合价范围内上下浮动10元',
						showCancel: false,
						success: function () {
							that.currentNum = that.menflag.toFixed(4);// 只能输入四个小数
						}
					})
				}
			},

			/**
			 * @author: MrLiu
			 * @time: 2021-09-15
			 * @Title: 列表
			 */
			getList() {
			
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
			
				console.log('传入参数' + this.prjId );
			
				uni.request({
					url: uni.getStorageSync('url') + "/pms/app/service/queryValuationDetails?prjId=" + this.prjId,
					method: 'POST',
					dataType: 'json',
					timeout: 10000 * 60,
					header: {
						'pmsToken': uni.getStorageSync('pmsToken')
					},
					data: {
			
					},
					success: (res) => {
						uni.hideLoading();
						//console.log('列表数据:' + JSON.stringify(res));
			
						var data = res.data;
						var result = JSON.stringify(data)
						console.log('列表数据:' + result);
						if (data.resultStat == "000") {
						
						this.baseList = data.valuationInfo
						for (var i = 0; i < data.valuationInfo.length; i++) {
							let obj = new Object
							obj.name = data.valuationInfo[i].serviceName
							obj.flag = false
							obj.valuationId = data.valuationInfo[i].valuationId
							obj.payType = "PROGRESSING",
							obj.currentInspectionNum ="",
							obj.currentInspectionMoney ="",
							obj.projectProgress="",
							obj.action="new",
							this.addlist.push(obj)
						}
						console.log('列表数据:' + JSON.stringify(this.addlist));
						} else {
							uni.showModal({confirmColor: '#eb4b4b',
								title: '温馨提示',
								content: data.message,
								showCancel: false,
							})
						}
			
						uni.hideLoading();
						uni.stopPullDownRefresh();
			
					},
					fail: (data, code) => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
						console.log('fail' + JSON.stringify(data));
					}
				});
			
			},
		/**
			 * @author: MrLiu
			 * @time: 2021-11-23
			 * @Title: 保存
			 */
			getCheckParams(params){
				let that=this;
				return new Promise((resolve,reject) => {
					if(params.length == 0){
						uni.showModal({
							confirmColor: '#eb4b4b',
							title: '温馨提示',
							content: "未勾选任何服务",
							showCancel: false,
							success: function () {
								that.leijiNum = ""//清空所有数据
								that.leijiMen = ""//清空所有数据
								that.addlist = []//清空所有数据
								that.getList()

							}
						})
						reject('fail')
					}else{
						resolve('success')
					}
				});
			},
			getSaveResult(data){
				if (data.resultStat == "000") {
					uni.showModal({
						confirmColor: '#eb4b4b',
						title: '温馨提示',
						content: data.message,
						showCancel: false,
						success: function () {
							//该方法用于刷新父页面
							uni.navigateBack({
								delta: 1
							})
						}
					})
				} else {
					uni.showModal({
						confirmColor: '#eb4b4b',
						title: '温馨提示',
						content: data.message,
						showCancel: false,
					})
				}
			},
			async save() {
				let that = this
				let params = that.addlist.filter(item=> item.flag === true)
				//判断是否勾选
				await this.getCheckParams(params);
				console.log("参数"+JSON.stringify(params))
				//校验字段	
				for (var i = 0; i < params.length; i++) {
					if(params[i].projectProgress==""){
						uni.showModal({confirmColor: '#eb4b4b',
							title: '温馨提示',
							content: params[i].name+"请输入项目进度",
							showCancel: false,
						})
						return;
					}
					if(params[i].currentInspectionNum==""){
						uni.showModal({confirmColor: '#eb4b4b',
							title: '温馨提示',
							content: params[i].name+"请输入本期验工数量",
							showCancel: false,
						})
						return;
					}
					if(params[i].currentInspectionMoney==""){
						uni.showModal({confirmColor: '#eb4b4b',
							title: '温馨提示',
							content: params[i].name+"请输入本期验工金额",
							showCancel: false,
						})
						return;
					}
					
				}
				
				
			
				
				console.log('最终提交' + JSON.stringify(params));
				
			
				
		uni.showModal({
			confirmColor: '#eb4b4b',
			title: '温馨提示',
			content: "是否确认提交",
			success: function (res2) {
			if (res2.confirm) {
                uni.showLoading({
                    title: '加载中...',
                    mask: true
                });
				//console.log('传入参数' + that.currentNum);	
				 	  
				uni.request({
					url: uni.getStorageSync('url') + "/pms/app/service/addValuationDetail",
					method: 'POST',
					dataType: 'json',
					timeout: 10000 * 60,
					header: {
						'pmsToken': uni.getStorageSync('pmsToken')
					},
					data:params,
					
					success: (res) => {
						uni.hideLoading();
						var data = res.data;
						var result = JSON.stringify(data)
						console.log('列表数据:' + result);
						that.getSaveResult(data);
						uni.hideLoading();
						uni.stopPullDownRefresh();
					},
					fail: (data, code) => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
						console.log('fail' + JSON.stringify(data));
					}
				});
				
				}
			}
		})	
		},

		}
	}
</script>


<style>
	@import '@/common/common-ui.css';
</style>
